package com.fyp.ptma.controllers;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fyp.ptma.dao.service.iservice.IUserService;
import com.fyp.ptma.model.Registration;
import com.fyp.ptma.model.User;
import com.fyp.ptma.property.PropertyFile;

@Controller
public class LinkNavigation extends AbstractController {
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@Autowired
	private IUserService userService;
	@Autowired
	private RegistrationValidation registrationValidation;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model, HttpServletRequest request) {

		 
		model.addAttribute("pageTitle", PropertyFile.valueOf("ptma.string"));
		model.addAttribute("ptma", PropertyFile.valueOf("app.name.abbrivation"));
		model.addAttribute("slogon", PropertyFile.valueOf("app.slogon"));
		return "index";
	}

	@RequestMapping(value = "/login.html", method = RequestMethod.GET)
	public ModelAndView login(Model model) {

		model.addAttribute("pageTitle",
				PropertyFile.valueOf("login.page.title"));

		model.addAttribute("appName",
				PropertyFile.valueOf("app.name.camelcase"));

		return new ModelAndView("login");
	}

	@RequestMapping(value = "/register.html", method = RequestMethod.GET)
	public ModelAndView register(Locale locale, Model model) {

		return new ModelAndView("registration");
	}

	@ResponseBody
	@RequestMapping(value = "/processRegistration.html", method = RequestMethod.POST)
	public String processRegistration(
			@ModelAttribute("registration") Registration registration,
			Model model, BindingResult result) {

		// set custom Validation by user
		registrationValidation.validate(registration, result);
		if (result.hasErrors()) {
			return "registration.html";
		} else {

			User user = new User();
			user.setEmail(registration.getEmail().toLowerCase());
			user.setPassword(registration.getPassword());
			user.setPhoneNumber(registration.getPhoneNumber());
			user.setFirstName(registration.getFirstName());
			user.setLastName(registration.getLastName());
			userService.save(user);
			return "login.html";
		}

	}
}
